package com.controller;

import javax.jws.WebParam.Mode;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bean.User;
import com.service.UserService;

@RequestMapping("user")
@Controller
public class UserController {
	@Autowired
 private UserService userService;
	@RequestMapping("/index")
	public String index() {
		return "index";
		
	}
	
	@RequestMapping("/login1")
	public String login1(@ModelAttribute("user")User user) {
		User tuser=userService.findByNameAndPw(user);
		if (tuser==null) {
			return "index";
		}
		
		return "list";
		
	}
	
	@RequestMapping("/login2")
	public String login2(User user,Model model) {
		User tuser=userService.findByNameAndPw(user);
		if (tuser==null) {
			return "index";
		}
		model.addAttribute("user", tuser);
		return "list";
		
	}
	
	@RequestMapping("/login3")
	public String login3(User user,HttpServletRequest request) {
		User tuser=userService.findByNameAndPw(user);
		if (tuser==null) {
			return "index";
		}
		request.setAttribute("user", tuser);
		return "list";
		
	}
	
	@RequestMapping("/login4")
	public ModelAndView login4(User user) {
		ModelAndView mv=new ModelAndView();
		User tuser=userService.findByNameAndPw(user);
		if (tuser==null) {
			mv.setViewName("index");
		}
		mv.setViewName("redirect:/emp/list");
		mv.addObject("user",tuser);
		return mv;
		
	}
	
	@RequestMapping("/login")
	public String login(User user,Model model) {
		User tuser=userService.findByNameAndPw(user);
		if (tuser==null) {
			return "index";
		}
		model.addAttribute("user",tuser);
		//重定向
		return "redirect:/emp/list";
		
	}
	
	@RequestMapping("/toregister")
	public String toregister() {
		return "userAdd";
		
	}

	@RequestMapping("/checkName")
	@ResponseBody//等价于out.write();
    public String checkName(String name) {
		User user=userService.checkName(name);
		String flag="0";
		if (user==null) {
			flag="0";
		}else{
			flag="1";
		}
		
		return flag;
		
	}
	
	@RequestMapping("/save")
	public String save(User user) {
	this.userService.save(user);
		return "index";
		
	}

}
